import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { productAPI } from '../api'

export const useProductStore = defineStore('product', () => {
  const products = ref([])
  const loading = ref(false)
  const error = ref(null)
  
  const fetchProducts = async () => {
    loading.value = true
    error.value = null
    try {
      const response = await productAPI.getProducts()
      products.value = response.data
    } catch (err) {
      error.value = err.message
      console.error('获取商品列表失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  const createProduct = async (productData) => {
    try {
      const response = await productAPI.createProduct({
        ...productData,
        createdAt: new Date().toISOString()
      })
      products.value.unshift(response.data)
      return response.data
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const updateProduct = async (id, productData) => {
    try {
      const response = await productAPI.updateProduct(id, productData)
      const index = products.value.findIndex(p => p.id === id)
      if (index !== -1) {
        products.value[index] = response.data
      }
      return response.data
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const deleteProduct = async (id) => {
    try {
      await productAPI.deleteProduct(id)
      products.value = products.value.filter(p => p.id !== id)
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const getProductById = (id) => {
    return products.value.find(p => p.id === parseInt(id))
  }
  
  const searchProducts = (keyword) => {
    if (!keyword) return products.value
    return products.value.filter(product => 
      product.name.toLowerCase().includes(keyword.toLowerCase()) ||
      product.description.toLowerCase().includes(keyword.toLowerCase()) ||
      product.category.toLowerCase().includes(keyword.toLowerCase())
    )
  }
  
  return {
    products,
    loading,
    error,
    fetchProducts,
    createProduct,
    updateProduct,
    deleteProduct,
    getProductById,
    searchProducts
  }
})